/*
 * 文件名：OtherCotController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年2月20日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.bpa.web;


import com.github.pagehelper.Page;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.mgr.bpa.domain.OtherCotAssist;
import top.infopub.mgr.bpa.domain.OtherCotDetailAndSubDomain;
import top.infopub.mgr.bpa.domain.OtherCotDomain;
import top.infopub.mgr.bpa.service.*;
import top.infopub.mgr.bpa.vo.OtherCotVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.bpa.*;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;


/**对内合同
 * @author wuzhiyang
 * @version 2020年2月20日
 * @see ProContractController
 * @since商务管理/对内合同/其他合同
 */
@Controller
@RequestMapping("/otherCot")
public class OtherCotController extends GenericFlowController {

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private OtherCotService otherCotService;

    @Autowired
    private ProContractService proContractService;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private ContractExtService contractExtService;

    @Autowired
    private ContractExtDetailService contractExtDetailService;

    @Autowired
    private ProContractDetailService proContractDetailService;

    @Autowired
    private OtherCotDetailService otherCotDetailService;

    @Autowired
    private OtherCotAttService otherCotAttService;

    @Autowired
    private OtherCotNodeService otherCotNodeService;

    @Autowired
    private OtherCotListService otherCotListService;

    @Autowired
    private OrgInfoService orgInfoService;

    /**
     * 其他合同列表
     * @return 
     * @see
     */
    @RequestMapping("/list")
    public String list() {
        return "bpa/lay-otherCot-list";
    }

    /**
     * 其他合同列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<OtherCotDomain> queryDataByCondition(OtherCotVo otherCotVo, ParamPage paramPage) {
        Page<OtherCotDomain> page = new Page<OtherCotDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (otherCotVo.getEndDate() != null) {
            otherCotVo.setEndDate(DateUtils.addDays(otherCotVo.getEndDate(), 1));
        }
        page = otherCotService.selectByDomainWhere(page, otherCotVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 其他合同-我审批的列表数据
     *
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<OtherCotDomain> queryMyCheckDataByCondition(OtherCotVo otherCotVo,
                                                             ParamPage paramPage) {
        Page<OtherCotDomain> page = new Page<OtherCotDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (otherCotVo.getEndDate() != null) {
            otherCotVo.setEndDate(DateUtils.addDays(otherCotVo.getEndDate(), 1));
        }
        otherCotVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = otherCotService.selectMyCheckByDomainWhere(page, otherCotVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 其他合同-新增
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //接收前端参数 判断 原合同  和  补充协议
        String types = request.getParameter("types");
        if ("1".equals(types)) {
            //返回所有项目合同中的项目名称
            List<ProContract> proContractList = proContractService.selectAllContracts(null, null);
            request.setAttribute("proContractList", proContractList);
            //返回所有合作单位为其他单位的信息
            List<CoopInfo> coopInfoList = coopInfoService.selectAll(null, null, "9");
            request.setAttribute("coopInfoList", coopInfoList);
            return "bpa/lay-otherCot-add-1";
        }
        else if ("2".equals(types)) {
            //返回其他合同中的项目名称
            List<OtherCot> otherCotList = otherCotService.selectByOtherCots();
            request.setAttribute("otherCotList", otherCotList);
            return "bpa/lay-otherCot-add-2";
        }
        return null;
    }

    /**
     * 根据子项名称、费用类型、id查询前期已录金额
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOtherCotPreRecordAmount")
    @ResponseBody
    public Map<String, Object> getOtherCotPreRecordAmount(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        String proCode = request.getParameter("proCodeAndCodes");
        String[] split = proCode.split("\\_");
        String typeName = request.getParameter("typeName");
        String subName = request.getParameter("subName");
        try {
            OtherCot otherCot = otherCotService.selectAddTimeByProCode(split[0]);
            OtherCotDomain otherCotDomain = new OtherCotDomain();
            if (otherCot != null) {
                BigDecimal addupAmountTotal = otherCotDetailService.selectAddupAmountBySubNameAndRefId(
                    subName, otherCot.getId(), typeName);
                if (addupAmountTotal == null) {
                    otherCotDomain.setAddupAmountTotal(BigDecimal.ZERO);
                    otherCotDomain.setAddupAmountFee(BigDecimal.ZERO);
                }
                else {
                    otherCotDomain.setAddupAmountTotal(addupAmountTotal);
                    otherCotDomain.setAddupAmountFee(addupAmountTotal);
                }
                otherCotDomain.setInContractFee(BigDecimal.ZERO);
                map.put("otherCotDomain",otherCotDomain);
            }
        }
        catch (Exception e) {
            log.error("查询前期已录金额异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

//    /**
//     * 根据项目合同中项目编号查询相关带入信息(其他合同/原合同)
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/getOtherCotByProCode")
//    @ResponseBody
//    public Map<String, Object> getProContractByProCode(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String proCode = request.getParameter("proCodeAndCodes");
//        String[] split = proCode.split("\\_");
//        String cotType = request.getParameter("cotType");
//        try {
//            //主表信息
//            ProContractDomain contractProCode = proContractService.selectByContractProCode(split[0]);
//            OtherCot otherCot = otherCotService.selectAddTimeByProCode(split[0]);
//            if (contractProCode != null) {
//                map.put("contractProCode", contractProCode);
//                //带出清单信息
//                ContractExt contractExt = contractExtService.selectByProCode(split[0]);
//                map.put("contractExt", contractExt);
//                if (contractExt != null) {
//                    if ("32".equals(cotType)) {
//                        List<ContractExtDetailAndSubDomain> selectDetailAndSubList = contractExtDetailService.selectDetailAndSub(
//                            contractExt.getId(), null, "3", "32", null, null);
//                        List<ContractExtDetailAndSubDomain> list = new ArrayList<>();
//                        for (ContractExtDetailAndSubDomain cSubDomain : selectDetailAndSubList) {
//                            String newOrderIdx = cSubDomain.getOrderIdx().replace("3.2", "1");
//                            cSubDomain.setOrderIdx(newOrderIdx);
//                            if (otherCot != null) {
//                                BigDecimal addupAmountTotal = otherCotDetailService.selectAddupAmountBySubNameAndRefId(
//                                    cSubDomain.getSubName(), otherCot.getId(),
//                                    cSubDomain.getTypeName());
//                                if (addupAmountTotal == null) {
//                                    cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                                }
//                                cSubDomain.setAddupAmountTotal(addupAmountTotal);
//                            }
//                            else if (otherCot == null) {
//                                cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                            }
//                            list.add(cSubDomain);
//                        }
//                        map.put("selectDetailAndSubList", list);
//                    }
//                    else if ("33".equals(cotType)) {
//                        List<ContractExtDetailAndSubDomain> selectDetailAndSubList = contractExtDetailService.selectDetailAndSub(
//                            contractExt.getId(), null, "3", null, "33", null);
//                        List<ContractExtDetailAndSubDomain> list = new ArrayList<>();
//                        for (ContractExtDetailAndSubDomain cSubDomain : selectDetailAndSubList) {
//                            String newOrderIdx = cSubDomain.getOrderIdx().replace("3.3", "1");
//                            cSubDomain.setOrderIdx(newOrderIdx);
//                            if (otherCot != null) {
//                                BigDecimal addupAmountTotal = otherCotDetailService.selectAddupAmountBySubNameAndRefId(
//                                    cSubDomain.getSubName(), otherCot.getId(),
//                                    cSubDomain.getTypeName());
//                                if (addupAmountTotal == null) {
//                                    cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                                }
//                                cSubDomain.setAddupAmountTotal(addupAmountTotal);
//                            }
//                            else if (otherCot == null) {
//                                cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                            }
//                            list.add(cSubDomain);
//                        }
//                        map.put("selectDetailAndSubList", list);
//                    }
//                }
//                else {
//                    if ("32".equals(cotType)) {
//                        List<ProContractDetailAndSubDomain> selectDetailAndSubList = proContractDetailService.selectDetailAndSub(
//                            contractProCode.getId(), null, "3", "32", null, null);
//                        List<ProContractDetailAndSubDomain> list = new ArrayList<>();
//                        for (ProContractDetailAndSubDomain cSubDomain : selectDetailAndSubList) {
//                            String newOrderIdx = cSubDomain.getOrderIdx().replace("3.2", "1");
//                            cSubDomain.setOrderIdx(newOrderIdx);
//                            if (otherCot != null) {
//                                BigDecimal addupAmountTotal = otherCotDetailService.selectAddupAmountBySubNameAndRefId(
//                                    cSubDomain.getSubName(), otherCot.getId(),
//                                    cSubDomain.getTypeName());
//                                if (addupAmountTotal == null) {
//                                    cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                                }
//                                cSubDomain.setAddupAmountTotal(addupAmountTotal);
//                            }
//                            else if (otherCot == null) {
//                                cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                            }
//                            list.add(cSubDomain);
//                        }
//                        map.put("selectDetailAndSubList", list);
//                    }
//                    else if ("33".equals(cotType)) {
//                        List<ProContractDetailAndSubDomain> selectDetailAndSubList = proContractDetailService.selectDetailAndSub(
//                            contractProCode.getId(), null, "3", null, "33", null);
//                        List<ProContractDetailAndSubDomain> list = new ArrayList<>();
//                        for (ProContractDetailAndSubDomain cSubDomain : selectDetailAndSubList) {
//                            String newOrderIdx = cSubDomain.getOrderIdx().replace("3.3", "1");
//                            cSubDomain.setOrderIdx(newOrderIdx);
//                            if (otherCot != null) {
//                                BigDecimal addupAmountTotal = otherCotDetailService.selectAddupAmountBySubNameAndRefId(
//                                    cSubDomain.getSubName(), otherCot.getId(),
//                                    cSubDomain.getTypeName());
//                                if (addupAmountTotal == null) {
//                                    cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                                }
//                                cSubDomain.setAddupAmountTotal(addupAmountTotal);
//                            }
//                            else if (otherCot == null) {
//                                cSubDomain.setAddupAmountTotal(BigDecimal.ZERO);
//                            }
//                            list.add(cSubDomain);
//                        }
//                        map.put("selectDetailAndSubList", list);
//                    }
//                }
//            }
//        }
//        catch (Exception e) {
//            log.error("查询项目合同记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 根据项目合同中项目编号查询相关带入信息(其他合同/补充合同)
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOtherCotSaByProCode")
    @ResponseBody
    public Map<String, Object> getOtherCotSaByProCode(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        String proCode = request.getParameter("proCodeAndCodes");
        String[] split = proCode.split("\\_");
        try {
            //主表信息
            OtherCotDomain otherCotDomain = otherCotService.selectNewsByProCode(split[1]);
            if (otherCotDomain != null) {
                map.put("otherCotDomain", otherCotDomain);
                //带出清单信息
                List<OtherCotDetailAndSubDomain> selectDetailAndSubList = otherCotDetailService.selectDetailAndSub(
                    otherCotDomain.getId(), null, null);
                map.put("selectDetailAndSubList", selectDetailAndSubList);
                //费用清单
                List<OtherCotList> selectOtherCotLists = otherCotListService.selectOtherCotLists(otherCotDomain.getId());
                map.put("selectOtherCotLists", selectOtherCotLists);
                //付款节点
                List<OtherCotNode> selectOtherCotNodeLists = otherCotNodeService.selectOtherCotNodeLists(otherCotDomain.getId());
                map.put("selectOtherCotNodeLists", selectOtherCotNodeLists);
                //附件
                List<OtherCotAtt> selectOtherCotAttLists = otherCotAttService.selectOtherCotAttLists(otherCotDomain.getId());
                map.put("selectOtherCotAttLists", selectOtherCotAttLists);
            }
        }
        catch (Exception e) {
            log.error("查询其他合同记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 分包合同-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(OtherCotAssist otherCotAssist) {

        //主表-分包合同
        otherCotAssist.setHrDeptId(otherCotAssist.getHrDeptid());
        otherCotAssist.setHrOrgId(otherCotAssist.getHrOrgid());
        otherCotAssist.setStaffName(otherCotAssist.getStaffname());
        otherCotAssist.setHrStaffApplyId(otherCotAssist.getHrStaffApplyid());
        String proCode = "";
        String code = "";
        String[] strCodes = otherCotAssist.getProCodeAndCodes().split("\\_");
        proCode = strCodes[0];
        code = strCodes[1];
        otherCotAssist.setProCode(proCode);
        //父关联id  第一次添加时为  原合同
        otherCotAssist.setRefId(code);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        //添加项目名称
        otherCotAssist.setProName(strCodes[2]);
        otherCotAssist.setId(id);
        otherCotAssist.setAddBy(vo.getId());
        otherCotAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("bpa_other_cot");
        otherCotAssist.setCodes(codes);
        //合同类型  先设置成  原合同  如果是补充协议的话  就会在 下面if中 形成覆盖
        otherCotAssist.setExtType("1");
        //合同版本 先设置成   原合同  每次提交时都进行 累加
        otherCotAssist.setVersionNo(1);
        // 处理processId
        otherCotAssist.setProcessId(IdFactory.getUUIDUpper());
        otherCotAssist.setProcessStatus("1");//审批中
        otherCotAssist.setTypes("1");//PPP项目
        otherCotAssist.setUptBy(vo.getId());
        otherCotAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //其他合同付款节点
        List<OtherCotNode> otherCotNodes = new ArrayList<OtherCotNode>();
        //序号
        String[] showIdxNodes = otherCotAssist.getShowIdxNodes();
        if (showIdxNodes != null && showIdxNodes.length > 0) {
            for (int i = 0; i < showIdxNodes.length; i++ ) {
                String showIdxNode = showIdxNodes[i];
                String nodeName = otherCotAssist.getNodeNames()[i];
                String payRate = otherCotAssist.getPayRates()[i];
                String payAmount = otherCotAssist.getPayAmounts()[i];
                if (StringUtils.isEmpty(showIdxNode)) {
                    continue;
                }
                OtherCotNode otherCotNode = new OtherCotNode();
                String otherCotNodeId = IdFactory.getUUIDUpper();//自动生成主键
                otherCotNode.setId(otherCotNodeId);
                otherCotNode.setOtherCotId(id);
                otherCotNode.setOrderIdx(Integer.parseInt(showIdxNode));
                otherCotNode.setPayAmount(new BigDecimal(payAmount));
                otherCotNode.setPayRate(new BigDecimal(payRate));
                otherCotNode.setNodeName(nodeName);
                otherCotNode.setAddBy(vo.getId());
                otherCotNode.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                otherCotNodes.add(otherCotNode);
            }
        }

        //新增其他合同分解子项
        List<OtherCotSub> otherCotSubs = new ArrayList<OtherCotSub>();
        //其他合同清单分解子项费用明细
        List<OtherCotDetail> otherCotDetails = new ArrayList<OtherCotDetail>();
        //清单模式
        List<OtherCotList> otherCotLists = new ArrayList<OtherCotList>();
        if ("2".equals(otherCotAssist.getJudge())) {
            //判断补充协议名称是否存在
            List<OtherCot> otherCot = otherCotService.isExistOtherCotSaName(
                otherCotAssist.getOtherCotSaName(), proCode);
            if (CollectionUtils.isNotEmpty(otherCot)) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("补充协议名称【"
                                                                + otherCotAssist.getOtherCotSaName()
                                                                + "】已经存在~");
            }
            //合同类型  覆盖上面的合同类型
            otherCotAssist.setExtType("2");
            //合同版本  每次提交时都进行 累加
            OtherCot otherCot2 = new OtherCot();
            otherCot2.setRefId(code);
            List<OtherCot> entityWhere = otherCotService.selectByEntityWhere(otherCot2);
            int versionNo = entityWhere.size() + 2;
            otherCotAssist.setVersionNo(versionNo);
            otherCotAssist.setRefId(code);
        }
        else {
            //判断其他合同名称是否存在
            List<OtherCot> otherCot = otherCotService.isExistOtherCotName(
                otherCotAssist.getOtherCotName(), proCode);
            if (CollectionUtils.isNotEmpty(otherCot)) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("其他合同名称【"
                                                                + otherCotAssist.getOtherCotName()
                                                                + "】已经存在~");
            }
        }

        //子项名称
        String[] subNames = otherCotAssist.getSubNames();
        if (subNames != null && subNames.length > 0) {
            for (int i = 0; i < subNames.length; i++ ) {
                String subName = subNames[i];
                if (StringUtils.isEmpty(subName)) {
                    continue;
                }
                OtherCotSub otherCotSub = new OtherCotSub();
                String otherCotSubId = IdFactory.getUUIDUpper();//自动生成主键
                otherCotSub.setId(otherCotSubId);
                otherCotSub.setOtherCotId(id);
                otherCotSub.setSubName(subName);
                otherCotSub.setAddBy(vo.getId());
                Date addTime = top.infopub.mgr.util.DateUtils.addSeconds(
                    top.infopub.mgr.util.DateUtils.getCurrentDateTime(), i);
                otherCotSub.setAddTime(addTime);
                otherCotSubs.add(otherCotSub);
            }

            //费用大类
            String[] feeSmallTypes = otherCotAssist.getFeeSmallTypes();
            for (int j = 0; j < feeSmallTypes.length; j++ ) {
                String feeSmallType = feeSmallTypes[j];
                String itemNameSub = otherCotAssist.getItemNameSub()[j];
                String typeName = otherCotAssist.getTypeNames()[j];
                String orderIdx = otherCotAssist.getOrderIdxs()[j];
                String outOrInnerAmount = otherCotAssist.getOutOrInnerAmounts()[j];
                String outCotAmount = otherCotAssist.getOutCotAmounts()[j];
                String beforeAmount = otherCotAssist.getBeforeAmounts()[j];
                String addupAmount = otherCotAssist.getAddupAmounts()[j];
                String outRestAmount = otherCotAssist.getOutRestAmounts()[j];
                if (StringUtils.isEmpty(feeSmallType)) {
                    continue;
                }
                OtherCotDetail otherCotDetail = new OtherCotDetail();
                String otherCotDetailId = IdFactory.getUUIDUpper();//自动生成主键
                otherCotDetail.setId(otherCotDetailId);

                otherCotDetail.setCotSubId(itemNameSub);

                otherCotDetail.setOtherCotId(id);
                otherCotDetail.setOrderIdx(orderIdx);
                otherCotDetail.setTypeName(typeName);
                String[] split = orderIdx.split("\\.");
                if (split.length == 1) {
                    otherCotDetail.setFeeSmallType(Integer.parseInt(feeSmallType));
                    otherCotDetail.setLevels(Integer.parseInt("1"));
                }
                else if (split.length == 2) {
                    String feeSmallType2 = feeSmallType.charAt(0) + "" + feeSmallType.charAt(2);
                    otherCotDetail.setFeeSmallType(Integer.parseInt(feeSmallType2));
                    otherCotDetail.setLevels(Integer.parseInt("2"));
                }
                else if (split.length == 3) {
                    String feeSmallType3 = feeSmallType.charAt(0) + "" + feeSmallType.charAt(2);
                    otherCotDetail.setFeeSmallType(Integer.parseInt(feeSmallType3));
                    otherCotDetail.setLevels(Integer.parseInt("3"));
                }
                otherCotDetail.setOutOrInnerAmount(new BigDecimal(outOrInnerAmount));
                otherCotDetail.setOutCotAmount(new BigDecimal(outCotAmount));
                otherCotDetail.setBeforeAmount(new BigDecimal(beforeAmount));
                otherCotDetail.setAddupAmount(new BigDecimal(addupAmount));
                otherCotDetail.setOutRestAmount(new BigDecimal(outRestAmount));
                otherCotDetail.setAddBy(vo.getId());
                otherCotDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                otherCotDetails.add(otherCotDetail);
            }

            for (OtherCotDetail otherCotDetail : otherCotDetails) {
                for (OtherCotSub otherCotSub : otherCotSubs) {
                    if (otherCotDetail.getCotSubId().equals(otherCotSub.getSubName())) {
                        otherCotDetail.setCotSubId(otherCotSub.getId());
                        break;
                    }
                }
            }
        }
        //清单
        String[] showIdxLists = otherCotAssist.getShowIdxLists();
        if (showIdxLists != null && showIdxLists.length > 0) {
            for (int j = 0; j < showIdxLists.length; j++ ) {
                String showIdxList = showIdxLists[j];
                String subNameList = otherCotAssist.getSubNameLists()[j];
                String subUnitList = otherCotAssist.getSubUnitLists()[j];
                String cotNumList = otherCotAssist.getCotNumLists()[j];
                String cotUnitPriceList = otherCotAssist.getCotUnitPriceLists()[j];
                String cotSumPriceList = otherCotAssist.getCotSumPriceLists()[j];

                OtherCotList otherCotList = new OtherCotList();
                String otherCotListId = IdFactory.getUUIDUpper();//自动生成主键
                otherCotList.setId(otherCotListId);
                otherCotList.setOtherCotId(id);
                otherCotList.setShowIdx(Integer.parseInt(showIdxList));
                otherCotList.setSubName(subNameList);
                otherCotList.setSubUnit(subUnitList);
                otherCotList.setCotNums(new BigDecimal(cotNumList));
                otherCotList.setCotUnitPrice(new BigDecimal(cotUnitPriceList));
                otherCotList.setCotSumPrice(new BigDecimal(cotSumPriceList));
                otherCotList.setAddBy(vo.getId());
                otherCotList.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                otherCotLists.add(otherCotList);
            }
        }

        //上传附件
        //1=政府发函（选填）
        List<OtherCotAtt> otherCotAtts = new ArrayList<OtherCotAtt>();
        String[] fileAtt5 = otherCotAssist.getFileAtts5();
        if (fileAtt5 != null) {
            for (String file : fileAtt5) {
                OtherCotAtt otherCotAtt = createFileAtt(vo, id, file, otherCotAssist.getExtType());
                otherCotAtt.setTypes("5");
                otherCotAtts.add(otherCotAtt);
            }
        }
        //2=其他附件（选填）
        String[] fileAtt4 = otherCotAssist.getFileAtts4();
        if (fileAtt4 != null) {
            for (String file : fileAtt4) {
                OtherCotAtt otherCotAtt = createFileAtt(vo, id, file, otherCotAssist.getExtType());
                otherCotAtt.setTypes("4");
                otherCotAtts.add(otherCotAtt);
            }
        }
        otherCotService.saveOtherCot(otherCotAssist, otherCotSubs, otherCotLists, otherCotDetails,
            otherCotNodes, otherCotAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "商务管理 -对内合同-其他合同：项目名="
                                                              + otherCotAssist.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 其他合同-补充签订
     * @throws ParseException 
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/sign")
    @ResponseBody
    public RspVo sign(HttpServletRequest request, OtherCotVo otherCotVo)
        throws ParseException {
        String[] fileAtt5 = request.getParameterValues("fileAtt5");
        String[] fileAtt4 = request.getParameterValues("fileAtt4");

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = otherCotVo.getId();
        List<OtherCotAtt> otherCotAtts = new ArrayList<OtherCotAtt>();
        if (fileAtt5 != null) {
            for (String file : fileAtt5) {
                OtherCotAtt otherCotAtt = createFileAtt(vo, id, file, "1");
                otherCotAtt.setTypes("5");
                otherCotAtts.add(otherCotAtt);
            }
        }
        if (fileAtt4 != null) {
            for (String file : fileAtt4) {
                OtherCotAtt otherCotAtt = createFileAtt(vo, id, file, "1");
                otherCotAtt.setTypes("4");
                otherCotAtts.add(otherCotAtt);
            }
        }
        otherCotService.sign(otherCotVo, otherCotAtts);
        LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
            "商务管理 -对内合同-补充签订其他合同：项目名=" + otherCotVo.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    private OtherCotAtt createFileAtt(AuthorizationVO vo, String otherCotId, String file,
                                      String extType) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        OtherCotAtt fileAtt = new OtherCotAtt();
        if (extType.equals("1")) {
            fileAtt.setId(fileAttStr[2]);
        }
        else {
            fileAtt.setId(IdFactory.getUUIDUpper());
        }
        fileAtt.setOtherCotId(otherCotId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "otherCot";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传对内合同-分包合同附件-文件名:"
                                                                      + filePath + "，文件路径:"
                                                                      + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据分部分项名称和refId查询月累金额
     * @param id
     * @return
     */
    @RequestMapping("/getAddupAmountBySubNameAndRefId")
    @ResponseBody
    public Map<String, Object> getAddupAmountBySubNameAndRefId(String subName,
                                                               String proCodeAndCodes,
                                                               String typeName) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isBlank(subName) || StringUtils.isBlank(proCodeAndCodes)
            || StringUtils.isBlank(typeName)) {
            flag = false;
        }
        else {
            try {
                String[] split = proCodeAndCodes.split("\\_");
                String refId = split[1];
                BigDecimal addupAmountTotal = otherCotDetailService.selectAddupAmountBySubNameAndRefId(
                    subName, refId, typeName);
                map.put("addupAmountTotal", addupAmountTotal);
            }
            catch (Exception e) {
                log.error("查询对内建安产值确权记录异常", e);
                flag = false;
            }
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询设备合同详细  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 其他合同id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        OtherCotVo otherCotVo = otherCotService.queryById(id);
        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setProjectCode(otherCotVo.getProCode());
        orgInfo.setState(1);
        List<OrgInfo> orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        if (orgInfos.size() > 0) {
            otherCotVo.setOrgProName(orgInfos.get(0).getCompName());
            otherCotVo.setHrOrgProId(orgInfos.get(0).getId());
            OrgInfo parentOrgInfo = new OrgInfo();
            parentOrgInfo.setId(orgInfos.get(0).getParentId());
            parentOrgInfo.setState(1);
            List<OrgInfo> parentOInfos = orgInfoService.selectByEntityWhere(parentOrgInfo);
            if (parentOInfos.size() > 0) {
                otherCotVo.setOrgAreName(parentOInfos.get(0).getCompName());
                otherCotVo.setHrOrgAreaId(parentOInfos.get(0).getId());
            }
        }
        request.setAttribute("modelDetail", otherCotVo);
        map.put("otherCotVo", otherCotVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, otherCotVo.getProcessId());
        return new ModelAndView("bpa/lay-otherCot-detail", map);
    }

    /**
     * 其他合同原合同/补充合同-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        String extType = request.getParameter("extType");
        OtherCotVo otherCotVo = otherCotService.queryById(id);
        request.setAttribute("otherCot", otherCotVo);
        //返回所有合作单位为其他单位的信息
        List<CoopInfo> coopInfoList = coopInfoService.selectAll(null, null, "9");
        request.setAttribute("coopInfoList", coopInfoList);
        if ("1".equals(extType)) {
            return "bpa/lay-otherCot-copy-1";
        }
        else if ("2".equals(extType)) {
            return "bpa/lay-otherCot-copy-2";
        }
        return null;
    }

    /**
     * 根据其他合同id查询相关带入信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOtherCotById")
    @ResponseBody
    public Map<String, Object> getOtherCotById(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        String proCodeAndCodes = request.getParameter("sguid");
        String[] strCodes = proCodeAndCodes.split("\\_");
        try {
            OtherCotVo otherCotVo = otherCotService.queryById(strCodes[1]);
            map.put("otherCotVo", otherCotVo);
        }
        catch (Exception e) {
            log.error("查询其他合同记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }
}
